<?php

namespace app\common\model;

use think\Db;

class ShopOrderGoodsModel extends BaseModel
{
    protected $name = 'shop_order_goods'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    //读取器
    protected function getPromotionTypeTextAttr($value, $data)
    {
        $arr = ['0' => '正常商品', '1' => '预售商品', '2' => '限时抢购', '3' => '积分商品', '4' => '集采商品', '5' => '竞拍商品'];
        return $arr[$data['promotion_type']];
    }

    /**
     * 库存处理
     * @param $data ['sku_id'=>'购买量']
     * @param string $type 1:扣除库存 2:增加库存
     * @return bool
     */
    public function doStock($data,$type=1){
        $goodsSkuModel = new ShopGoodsSkuModel();
        $goodsModel = new ShopGoodsModel();
        $skuIds = array_keys($data);
        //商品库存信息
        $skuStockData = $goodsSkuModel->where('sku_id','in',$skuIds)->column('goods_id,goods_stock ,sale_number','sku_id');
        $goodsIds = array_column($skuStockData,'goods_id');
        $goodsStockData = $goodsModel->where('goods_id','in',$goodsIds)->column('goods_sale_number','goods_id');
        $skuStockList = [];
        $goodsStockList = [];
        $goodsStock = [];
        //计算SKU库存及销量
        foreach ($skuStockData as $skuId=>$v){
            if($type==1){ //扣除库存 增加销量
                $skuStock = ($v['goods_stock']-$data[$skuId]);
                $saleNumber = ($v['sale_number']+$data[$skuId]);
                $goodsStock[$v["goods_id"]]["goods_sale_number"] += $v["sale_number"];
            }
            if($type==2){ //增加库存 减少销量
                $skuStock = ($v['goods_stock']+$data[$skuId]);
                $saleNumber = ($v['sale_number']-$data[$skuId]);
                $goodsStock[$v["goods_id"]]["goods_sale_number"] -= $v["sale_number"];
            }
            $skuStockList[] = ['sku_id'=>$skuId,'goods_stock'=>$skuStock,'sale_number'=>$saleNumber];
        }
        //计算goods销量
        foreach($goodsStockData as $goodsId=>$goodsSaleNumber){
            if($type==1){ //增加销量
                $goodsStockList[] = ['goods_id'=>$goodsId,'goods_sale_number'=>($goodsStockData[$goodsId]+$goodsStock[$goodsId]["goods_sale_number"])];
            }
            if($type==2){ //减少销量
                $goodsStockList[] = ['goods_id'=>$goodsId,'goods_sale_number'=>($goodsStockData[$goodsId]-$goodsStock[$goodsId]["goods_sale_number"])];
            }
        }
        if(!empty($skuStockList)){
            $goodsSkuModel->saveAll($skuStockList);
            $goodsModel->saveAll($goodsStockList);
        }
        return true;
    }

}